<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="createNewRoot">新建目录</t-button>
          <template v-if="user.checkAuthCode('sys:role:test')">
            <t-button>sys:role:test</t-button>
          </template>
        </div>
        <div class="search-input">
          <t-button theme="default" @click="refreshTable">刷新表格</t-button>
        </div>
      </t-row>

      <dialog-form v-model:visible="formDialogVisible" :data="formData" @refresh-table="refreshTable" />

      <t-enhanced-table
        v-model:expandedTreeNodes="expandedTreeNodes"
        row-key="routeId"
        :data="data"
        :tree="treeConfig"
        :columns="columns"
        :header-affixed-top="headerAffixedTop"
        :loading="dataLoading"
        :pagination="pagination"
      >
        <template #type="{ row }">
          <template v-if="row.type === 0">
            <t-tag theme="primary" variant="outline">目录</t-tag>
          </template>
          <template v-if="row.type === 1">
            <t-tag theme="success" variant="outline">页面</t-tag>
          </template>
          <template v-if="row.type === 2">
            <t-tag theme="warning" variant="outline">按钮</t-tag>
          </template>
        </template>
        <template #createTime="{ row }">
          {{ `${dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}(${row.createUserName})` }}
        </template>
        <template #updateTime="{ row }">
          <template v-if="row.updateTime">
            {{ `${dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')}(${row.updateUserName})` }}
          </template>
        </template>
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="createNewChildren(slotProps)">新增</t-link>
            <t-link theme="primary" @click="handleClickDetail(slotProps)">编辑</t-link>
            <t-popconfirm content="确认删除吗？" theme="danger" @confirm="handleClickDelete(slotProps)">
              <t-link theme="danger">删除</t-link>
            </t-popconfirm>
            <!--            <t-link theme="danger" @click="handleClickDelete(slotProps)">删除</t-link>-->
          </t-space>
        </template>
      </t-enhanced-table>
    </t-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'AuthorityList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, PrimaryTableCol } from 'tdesign-vue-next';
import { computed, onMounted, reactive, ref } from 'vue';

import { loadTableList } from '@/api/list';
import { prefix } from '@/config/global';
import { useSettingStore, useUserStore } from '@/store';

import type { FormData } from './components/DialogForm.vue';
import DialogForm from './components/DialogForm.vue';
import { post } from '@/api/common';

const user = useUserStore();

const INITIAL_DATA: FormData = {
  routeId: null,
  path: '',
  code: '',
  type: 0,
  name: '',
  component: '',
  redirect: '',
  parentId: 0,
  meta: {
    metaId: null,
    title: '',
  },
};

const formData = ref({ ...INITIAL_DATA });

const store = useSettingStore();

const refreshTable = async () => {
  pagination.value.total = -1;
  await fetchData();
};

const expandedTreeNodes = ref([]);

const formDialogVisible = ref(false);

const treeConfig = reactive({
  treeNodeColumnIndex: 2,
  indent: 25,
  expandTreeNodeOnClick: true,
});

const handleClickDelete = async (data: any) => {
  if (data.row.children.length > 0) {
    MessagePlugin.warning('子集还有数据无法删除！');
  } else {
    await post(`/sysRoute/remove/${data.row.routeId}`, {});
    await refreshTable();
  }
  // console.log('data.row', data.row);
  // router.push('/detail/base');
  // formData.value = { ...data.row };
  // formDialogVisible.value = true;
  // console.log(user.checkAuthCode(''));
  // await post('', {});
};

const handleClickDetail = (data: any) => {
  // router.push('/detail/base');
  formData.value = { ...data.row };
  formDialogVisible.value = true;
  // console.log(user.checkAuthCode(''));
};

const columns: PrimaryTableCol[] = [
  { title: 'ID', colKey: 'routeId' },
  // { title: '父ID', colKey: 'parentId' },
  { title: '类型', colKey: 'type' },
  { title: '代码', colKey: 'code' },
  { title: '标题', colKey: 'meta.title' },
  { title: '路径', colKey: 'path' },
  { title: '名称', colKey: 'name' },
  { title: '组件', colKey: 'component' },
  { title: '重定向', colKey: 'redirect' },
  { title: '创建', colKey: 'createTime' },
  { title: '更新', colKey: 'updateTime' },
  { title: '操作', colKey: 'op', width: 150 },
];

const data = ref([]);
const pagination = ref({
  defaultPageSize: 1000,
  total: -1,
  defaultCurrent: 1,
});

const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list, total } = await loadTableList('/sysRoute/table', {
      // @ts-ignore
      current: pagination.value.current || pagination.value.defaultCurrent,
      // @ts-ignore
      pageSize: pagination.value.pageSize || pagination.value.defaultPageSize,
      total: pagination.value.total,
    });
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

onMounted(() => {
  fetchData();
});

const createNewRoot = () => {
  formDialogVisible.value = true;
};

const createNewChildren = (data) => {
  formData.value = { ...INITIAL_DATA, parentId: data.row.routeId };
  // console.log('routeId', data.row.routeId);
  formDialogVisible.value = true;
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any,
);
</script>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);

  .selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-l);
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  //width: 360px;
}
</style>
